package com.liuwei.netty.reconnect;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {
    public static void main(String[] args) {
        // 只处理连接的线程
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //如果不手动指定数量就默认为是CPU核实数的两倍
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            // 创建服务端启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 配置参数
            bootstrap.group(bossGroup, workGroup) //配置group
                    // 使用NioServerSocketChannel作为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 配置存放因为没有空间被暂存的队列，及其队列长度
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 创建通道初始化的对象并配置对象，向该对象添加处理器完成业务操作
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            // 添加业务出路handle
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            log.info("Netty服务端启动了........");
            // 启动服务器,同步阻塞
            ChannelFuture channelFuture = bootstrap.bind(9090).sync();

            // 监听端口
            channelFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        log.info("监听9090端口成功了");
                    } else {
                        log.info("监听9090端口失败了");
                    }
                }
            });
            // 只要服务没有关闭，该方法会一直阻塞
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
